package com.example.s.Activity.search;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.example.s.Activity.BaseActivity;
import com.example.s.R;
import com.example.s.adapter.InnerHolder;
import com.example.s.adapter.MyFragmentPagerAdapter;
import com.example.s.adapter.MyRecyclerViewAdapter;
import com.example.s.fragment.search.HotestFragment;
import com.example.s.fragment.search.LatestFragment;
import com.example.s.view.MyDialog;
import com.nex3z.flowlayout.FlowLayout;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class SearchActivity extends BaseActivity {
    private ImageView back;
    private EditText keywords;
    private RelativeLayout historyContainer;
    private ImageView delHistory;
    private FlowLayout historyItemContainer;
    private RelativeLayout hotSearchContainer;
    private TextView hotTitle;
    private RecyclerView HotSearchContainer;
    private HashSet<String> historyList = new HashSet<>(); //限定大小为  10
    private List<String> hotSearchList = new ArrayList<>();
    private MyRecyclerViewAdapter hotSearchAdapter;
    private RecyclerView HotSearchContainerRv;
    private RadioGroup searchRecNav;
    private ViewPager searchRecVp;
    private ScrollView sv;
    private LinearLayout navContainer;


    private void initView() {

        back = (ImageView) findViewById(R.id.back);
        keywords = (EditText) findViewById(R.id.keywords);
        historyContainer = (RelativeLayout) findViewById(R.id.historyContainer);
        delHistory = (ImageView) findViewById(R.id.delHistory);
        historyItemContainer = (FlowLayout) findViewById(R.id.historyItemContainer);
        hotSearchContainer = (RelativeLayout) findViewById(R.id.hotSearchContainer);
        hotTitle = (TextView) findViewById(R.id.hotTitle);
        HotSearchContainer = (RecyclerView) findViewById(R.id.HotSearchContainerRv);
        HotSearchContainerRv = (RecyclerView) findViewById(R.id.HotSearchContainerRv);
        searchRecNav = (RadioGroup) findViewById(R.id.searchRecNav);
        searchRecVp = (ViewPager) findViewById(R.id.searchRecVp);
        sv = (ScrollView) findViewById(R.id.sv);
        navContainer = (LinearLayout) findViewById(R.id.navContainer);


    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        initView();


        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        keywords.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if ((actionId == 0 || actionId == 3) && event != null) {
                    //点击搜索要做的操作
                    String k = v.getText().toString();
                    if (TextUtils.isEmpty(k))
                        return false;
                    search(k);
                }
                return false;
            }
        });

//"男士发型","期末好作品","java代码源码","关于光影","原创成品","穿搭推荐"
        hotSearchList.add("期末好作品");
        hotSearchList.add("java代码源码");
        hotSearchList.add("关于光影");
        hotSearchList.add("穿搭推荐");
        hotSearchList.add("男士发型");
        HotSearchContainer.setLayoutManager(new GridLayoutManager(this, 2));
        HotSearchContainer.setAdapter(hotSearchAdapter = new MyRecyclerViewAdapter<String>(hotSearchList, R.layout.fl_category_content_item) {
            @Override
            public void handleData(InnerHolder holder, String item) {
                TextView label = holder.getView(R.id.label);
                label.setText(item);
                label.setTextSize(14);
                holder.setOnClickListener(R.id.item, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        keywords.setText(item);
                        search(item);
                    }
                });
            }
        });

        /**
         * 删除历史记录
         */final MyDialog[] myDialog = new MyDialog[1];
        delHistory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myDialog[0] = new MyDialog(SearchActivity.this, new MyDialog.OnMyDialogListener() {
                    @Override
                    public void handleDialog(InnerHolder holder) {
                        holder.setText(R.id.title, "确定要删除历史记录吗？")
                                .setOnClickListener(R.id.confirm, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        removeHistoryAll();
                                        historyItemContainer.removeAllViews();
                                        myDialog[0].disMyDialog();
                                    }
                                });
                    }
                });
            }
        });

        /**
         * 搜索推荐  内容  导航
         */
        searchRecNav.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                for (int i = 0; i < group.getChildCount(); i++) {
                    RadioButton btn = (RadioButton) group.getChildAt(i);
                    btn.setTextColor(Color.parseColor("#FFE2E2E2"));
                    btn.setTextSize(12);
                }
                RadioButton btn = group.findViewById(checkedId);
                btn.setTextColor(Color.parseColor("#FFD9408A"));
                btn.setTextSize(16);
                if ("最热".contentEquals(btn.getText())) {
                    searchRecVp.setCurrentItem(0);
                } else {
                    searchRecVp.setCurrentItem(1);

                }
            }
        });

        setSearchRecContent();

        /**
         * 吸顶灯
         */
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            final boolean[] flag = {false};
            final float[] y = {0}; //joke 导航的y
            sv.setOnScrollChangeListener(new View.OnScrollChangeListener() {
                @SuppressLint("ResourceAsColor")
                @Override
                public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                    Log.d(TAG, "onScrollChange: ");
                    if (!flag[0]) {
                        y[0] = navContainer.getY();
                        flag[0] = true;
                    }
                    if (oldScrollY > y[0]) {
                        navContainer.setY(scrollY);
                        navContainer.setBackgroundColor(Color.parseColor("#000038"));
                    } else {
                        //开始吸顶
                        navContainer.setY(y[0]);
                        navContainer.setBackgroundColor(android.R.color.transparent);
                    }
                }
            });
        }
    }

    private void search(String k) {
        if (!historyList.contains(k)) {
            addHistoryLabel(k);
            historyList.add(k);
        }

    }

    @Override
    protected void onStop() {
        super.onStop();
        //存储历史list
        Log.d(TAG, "onStop: 存储历史list");
        getSharedPreferences("searchHistory").edit().putStringSet("history", historyList).commit();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //获取之前的搜索记录
        Log.d(TAG, "onResume:获取 历史list");
        Set<String> stringSet = getSharedPreferences("searchHistory").getStringSet("history", new HashSet<String>());
        historyList.clear();
        historyList.addAll(stringSet);
        addHistoryLabelAll(historyList);
    }

    private void setSearchRecContent() {
        List<Fragment> searchRecList = new ArrayList<>();
        HotestFragment hotestFragment = new HotestFragment();
        LatestFragment latestFragment = new LatestFragment();
        searchRecList.add(hotestFragment);
        searchRecList.add(latestFragment);
        searchRecVp.setAdapter(new MyFragmentPagerAdapter(getSupportFragmentManager(), searchRecList));
        searchRecVp.setOffscreenPageLimit(2);
        searchRecVp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                for (int i = 0; i < searchRecNav.getChildCount(); i++) {
                    RadioButton btn = (RadioButton) searchRecNav.getChildAt(i);
                    btn.setTextColor(Color.parseColor("#FFE2E2E2"));
                    btn.setTextSize(12);
                }
                RadioButton btn = (RadioButton) searchRecNav.getChildAt(position);
                btn.setTextColor(Color.parseColor("#FFD9408A"));
                btn.setTextSize(16);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void addHistoryLabelAll(HashSet<String> historyList) {
        for (String s : historyList) {
            addHistoryLabel(s);
        }
    }


    private void addHistoryLabel(String title) {
        View item = LayoutInflater.from(this).inflate(R.layout.fl_history_item, null);
        TextView label = item.findViewById(R.id.label);
        label.setTextSize(14);
        label.setText(title);
        item.findViewById(R.id.del).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                historyItemContainer.removeView(item);
            }
        });
        item.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                keywords.setText(title);
                search(title);
            }
        });
        historyItemContainer.addView(item, 0);
    }


    private void removeHistoryAll() {
        historyList.clear();
    }
}
